import { navTo } from '../utils';
import { Toast } from 'vant';

const removeCookie = (app, key) => {
  // 没有指定的情况下，会删除当前完整域名下的 对应cookie，比如对应的 a.ydl.com
  app.$cookiz.remove(key);
  // 需要指定 path 和 domain 否则无法删除
  app.$cookiz.remove(key, {
    domain: '.ydl.com',
    path: '/',
  });
};

// formdata 文件流接口
const formDataUrls = ['/api/file/upload']

export default function (context, inject) {
  const { $axios, query, app } = context;

  $axios.setBaseURL(process.env.BASE_HOST_API);
  $axios.onRequest((config) => {
    const username = query.username || app.$cookiz.get('username') || '';
    const accessToken = query.accessToken || app.$cookiz.get('accessToken') || '';
    config.headers.username = encodeURIComponent(username);
    config.headers.accessToken = accessToken;
    if(formDataUrls.includes(config.url)){
      config.headers['Content-Type']='multipart/form-data'
    }
    return config;
  });

  $axios.onResponse((res) => {
    if (res.status === 200 && res.data) {
      if (+res.data.code === 200) {
        return Promise.resolve(res.data);
      } else if (+res.data.code === 401) {
        if (process.client) {
          removeCookie(app, 'username');
          removeCookie(app, 'accessToken');
          const isFromApp = query.isFromApp || app.$cookiz.get('isFromApp');
          if (isFromApp && process.env.NODE_ENV !== 'development') {
            // todo  去登录
          } else {
            //  微信小程序中打开的页面
            if (query?.isFromMin === 'weapp' && window.wx && window.wx.miniProgram) {
              window.wx.miniProgram.navigateTo({
                url: '/pages/login/login',
              });
            } else {
              navTo(`${process.env.BASE_URL_M}/login?sourceUrl=${window.location.href}`, true);
            }
          }
        }
        return Promise.reject();
      } else {
        // 自定义处理错误
        if (res.config.customHandleErr) {
          return Promise.reject({ ...res, customHandleErrFlag: true });
        }
        if (res.data.err_msg || res.data.errMsg || res.data.msg) {
          Toast.fail(res.data.err_msg || res.data.errMsg || res.data.msg);
        }
        return Promise.reject(res.data.err_msg || res.data.errMsg || res.data.msg);
      }
    } else {
      return Promise.reject(res);
    }
  });

  $axios.onError((error) => {
    return Promise.reject(error);
  });

  inject('http', $axios);
}
